<?php

namespace App\Http\Controllers\Wechat;

use App\Libs\ResponseMessage;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use Illuminate\Http\Request;

class ServerController {
    public function server(){
        try {
            $app = Factory::officialAccount(\Config::get('wechat.official_account.default'));
            $app->server->push(function ($message) use ($app) {
                \Log::debug($message);
                switch ($message['MsgType']) {
                    case 'event':
                        switch ($message['Event']) {
                            case 'unsubscribe':
                                break;
                            case 'subscribe':
                                $wechatText = <<<EOF
感谢您关注『果小贱』公众号

实体店『果小贱』为您的水果提供安全可靠的存储空间
公众号为您提供更方便的购买渠道以及多更多优惠方案

早上上班路上吃水果，为新的一天补充活力
晚上下班回家吃水果，赶走所有疲倦

赶快来『果小贱』将属于您的新鲜水果领回家吧！
EOF;
                                return $wechatText;
                                break;
                            case 'CLICK':
                                break;
                        }
                        break;
                    default:
                        return "有什么问题可以联系咱们的果小妹，电话：13077353616 微信：13077353616";
                        break;
                }
            });

            return $app->server->serve();
        }catch (\Exception $exception){
            \Log::error($exception);
        }
    }

    /**
     * 设置菜单
     */
    public function setMenu(){
        $menu = [
            [
                "type" => "view",
                "name" => "每天抽水果",
                "url"  => "http://guoxiaojian.guoxiaoge.cn/api/wechat/login?redirect=eat-every-day"
            ],
            [
                'type'      => 'miniprogram',
                'name'      => '商城',
                'url'       => 'http://mp.weixin.qq.com',
                'appid'     => 'wx826cb99445ebac03',
                'pagepath'  => 'pages/index/index'
            ],
        ];
        $app = Factory::officialAccount(\Config::get('wechat.official_account.default'));
        $app->menu->create($menu);
    }

    /**
     * 发送客服消息
     */
    public function sendStaff($openId , $type  , $content){
        try {
            $message = '';

            if ($type == 'text') {
                $message = new Text($content);
            } elseif ($type == 'img') {
                $message = new Image($content);
            } elseif ($type == 'news') {
                $newsItem = new NewsItem($content);
                $message = new News([$newsItem]);
            }

            if (!empty($message)) {
                $app = Factory::officialAccount(\Config::get('wechat.official_account.default'));
                $staff = $app->customer_service; // 客服管理
                return $staff->message($message)->to($openId)->send();
            } else {
                return false;
            }
        }catch (\Exception $exception){
            \Log::debug($exception);
        }
    }

    //获取微信js sdk
    /**
     *   [
     *      mehod : 'post',
     *      request_params : [
     *          'apis' : str,
     *          'debug' : true/false   //是否开启调试
     *      ]
     *      response : [
     *          'code' => 'xx'  1success  0 error
     *          'msg'  =>  '消息提示'
     *          'data' => xxx     返回数据
     *      ]
     *   ]
     */
    //参数1, api参数  2,是否开启调试 3不知道, 4是否返回json格式
    public function getJsSdk(Request $request)
    {
        $apis = $request->input('apis');
        if ($apis) {
            $apis_arr = explode(',', $apis);
        } else {
            $apis_arr = ['updateAppMessageShareData', 'updateTimelineShareData','checkJsApi'];
        }

        $app = Factory::officialAccount(\Config::get('wechat.official_account.default'));
        $js = $app->jssdk;

        $debug = false;
        if ($request->has('debug')) {
            $debug = $request->input('debug');
        }

        if ($request->has('url')) {
            $js->setUrl($request->get('url'));
        }
        $config = $js->buildConfig($apis_arr, $debug, $beta = false, $json = true);
        if (!empty($config)) {
            return response()->json(ResponseMessage::getInstance()->success($config)->response());
        } else {
            return response()->json(ResponseMessage::getInstance()->failed()->response());
        }

    }

    public function login(Request $request){
        $config = \Config::get('wechat.official_account.default');
        $config['oauth']['callback'] .= '?'.http_build_query($request->all());
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;
        return $oauth->redirect();
    }

    public function sendTempMsg($openId, $tempid, $data=[], $url){
        try {
            $app = Factory::officialAccount(\Config::get('wechat.official_account.default'));
            return $app->template_message->send([
                'touser' => $openId,
                'template_id' => $tempid,
                'url' => $url,
                'data' => $data,
            ]);
        }catch (\Exception $exception){
            \Log::error($exception);
        }
    }
}